<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use org\Jdk_inc;
use think\Request;
error_reporting(0);
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");

class Oauth extends Controller
{

    static private $app_id;
    static private $app_script;
    public $wx_info;
    public $wx_id = 1;
    public $url;
    public $father_id;
    public function __construct($wx_id=1)
    {
        $this->wx_id = $wx_id;
        $this->wx_info = db("weixin_config")->where("wx_id=".$this->wx_id)->find();
        self::$app_id  = $this->wx_info['wx_appid'];
        self::$app_script  = $this->wx_info['wx_appsecret'];

    }
    
        //微信小程序登录
    public function wxlogin(){
        $code = input('code');
        $wx = db('weixin_config')->where(['wx_id'=>2])->find();
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$wx['wx_appid'].'&secret='.$wx['wx_appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($res,true);
        $user = db('user')->where(['openid'=>$res['openid']])->find();
        // 看用户有没有登录过
        if($user){
            // 登录
            session("user_id",$user['user_id']);
            cookie("hotel",$user['user_id'],86400*30);
            db('user')->where(['user_id'=>$user['user_id']])->update(['wx_sessionkey'=>$res['session_key']]);
            // 判断用户有没有绑定手机号
            if($user['phone']){
                return array('code'=>1,'receive'=>1,'token'=>$user['user_id']);  
            }else{
                return array('code'=>1,'receive'=>0,'token'=>$user['user_id']);
            }
        }else{
            // 注册用户信息 并且登录
            $user_id = db('user')->insertGetId(['openid'=>$res['openid'],'wx_sessionkey'=>$res['session_key']]);
            vipnumber($user_id);
            session("user_id",$id);
            cookie("hotel",$id,86400*30);
            return array('code'=>1,'receive'=>0,'token'=>$user_id);
        }
    }
    // 微信小程序获取手机号
    public function getPhone(){
        $data = input('post.');
        $user_id = Request::instance()->header('token');
        if($user_id){
            // 获取appid
            $app_id = db('weixin_config')->where(['wx_id'=>2])->value('wx_appid');
            // 获取$sessionKey
            $sessionKey = db('user')->where(['user_id'=>$user_id])->value('wx_sessionkey');
            $encryptedData = $data['encryptedData'];
            $iv = $data['iv'];
            $appid = $app_id;
            $sessionKey = $sessionKey;

            $encryptedData=$data['encryptedData'];

            $iv = $iv;

            $pc = new WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );
            if ($errCode == 0) {
                $data = json_decode($data,true);
                $ok = db('user')->where(['user_id'=>$user_id])->update(['phone'=>$data['phoneNumber']]);
                if($ok){
                    return array('code'=>1,'msg'=>'绑定成功');
                }
            } else {
                return array('code'=>0,'msg'=>'请重新登录');
            }
        }
        
    }
    /****平台用户授权*****/
    public function index(){
        $father_id = input('father_id');
        db('log')->insert(['title'=>$father_id]);
        $this->url= urldecode(input('url'));
        $this->father_id = intval(input('father_id'));
        // file_put_contents('send.log', "1111-".$this->father_id . "\n", FILE_APPEND);
        // file_put_contents('send.log', "22-".$this->url . "\n", FILE_APPEND);
        $res = $this->check_auth();
        
        if(session('user_id'))
        {
            if($this->url){
                $url = $this->url;
            }else{
                $url = url("index/index");
            }
            header('Location:' .$url);exit;
        }
    }



    public  function check_auth()
    {
        
        $state 	= isset($_GET['state'])?$_GET['state']:0;
        //检测是否授权状态
        if (!session('user_id'))
        {
            if ($state)
            {
                $code = isset($_GET['code'])?$_GET['code']:0;
                
                if (!$code) {
                    exit('code error');
                }
                $token_url 	= 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::$app_id.'&secret='.self::$app_script.'&code='.$code.'&grant_type=authorization_code';
                $token_info=file_get_contents($token_url);

                $token_info = json_decode($token_info ,true);
                if (isset($token_info['errcode'])) {
                    exit('token error');
                }
                $auth_url 	= 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token_info['access_token'].'&openid='.$token_info['openid'].'&lang=zh_CN';
                $auth_info=file_get_contents($auth_url);
                $auth_info	= json_decode($auth_info,true);
                
                if(isset($auth_info['openid'])){
                    $user = db('user')->where('openid',$auth_info['openid'])->find();
                     if(!empty($user)){  //用户已存
                      
                          if($user['user_status']==1){
                                echo '<script>alert("账号已禁用")</script>';die;
                          }
                        
                         $update=[
                             'nickname'     =>$auth_info['nickname'],  
                             'avatar'      =>$auth_info['headimgurl'], 
                         ];
                         //会员卡编号操作
                         vipnumber($user['user_id']);
                         db("user")->where(['user_id'=>$user['user_id']])->update($update);
                         db('user')->where(['user_id'=>$user['user_id']])->setInc('login_num');
                         session("user_id",$user['user_id']); 
                         cookie("hotel",$user['user_id'],86400*30);
                         return true;
                     }else{
                         $wxuser=[
                             'openid'       =>$auth_info['openid'],
                             'nickname'     =>$auth_info['nickname'], 
                             'avatar'      =>$auth_info['headimgurl'], 
                             'sex'           =>$auth_info['sex'], 
                             "user_addtime"      =>time(),
                             "login_num"      =>1, 
                             "father_id"      =>$this->father_id, 
                         ];
                         
                         
                         $id=db("user")->insertGetId($wxuser);
                         
                         vipnumber($id);
                        
                         session("user_id",$id);
                         cookie("hotel",$id,86400*30);
                     }

                }else{
                    echo '<span style="font-size:30px;">获取信息失败</span>';die;
                }
            } else {
                $return_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                
                $return_url = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

                $location_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::$app_id.'&redirect_uri='.$return_url.'&response_type=code&scope=snsapi_userinfo&state=auth&connect_redirect=1#wechat_redirect';
                
                header("Location:".$location_url);
            }
        } else {
            return true;
        }
    }
    
    
     


}
